import time
import smtplib
from email.mime.text import MIMEText
import taosrest

# 邮件发送配置
SMTP_SERVER = 'smtp.qq.com'
SMTP_PORT = 465
SENDER_EMAIL = '2085632015@qq.com'
SENDER_PASSWORD = 'wqnwpeacztgpeagd'  # QQ邮箱授权码
RECEIVER_EMAIL = '3233249296@qq.com'

# TDengine连接配置
TDENGINE_URL = "http://192.168.1.251:6041"
TDENGINE_USER = "root"
TDENGINE_PASSWORD = "taosdata"
TDENGINE_DATABASE = "syslogdb"
TABLE_NAME = "syslog_logs_192_168_1_254"

# 查询配置
POLL_INTERVAL_SECONDS = 30  # 查询间隔
SEARCH_KEYWORD = 'error'    # 查询关键词

def send_email(subject: str, body: str):
    """发送邮件"""
    msg = MIMEText(body, 'plain', 'utf-8')
    msg['Subject'] = subject
    msg['From'] = SENDER_EMAIL
    msg['To'] = RECEIVER_EMAIL

    try:
        with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
            server.login(SENDER_EMAIL, SENDER_PASSWORD)
            result = server.sendmail(SENDER_EMAIL, [RECEIVER_EMAIL], msg.as_string())
            if result == {}:
                print(f"✅ 邮件已成功发送至 {RECEIVER_EMAIL}")
            else:
                print(f"⚠️ 邮件部分失败: {result}")
    except Exception as e:
        print(f"❌ 邮件发送过程异常: {e}")

def monitor_tdengine():
    """定时轮询TDengine，检测是否有错误日志"""
    conn = None
    last_sent_ts = None  # 上一次已发送的日志时间戳

    try:
        # 建立连接
        conn = taosrest.connect(
            url=TDENGINE_URL,
            user=TDENGINE_USER,
            password=TDENGINE_PASSWORD
        )
        cursor = conn.cursor()
        print("✅ 成功连接到 TDengine (REST模式)。开始监控...")

        while True:
            try:
                # 查询最新一条包含 'error' 的日志，包括翻译内容
                sql = f"""
                SELECT ts, source_ip, full_message, translated_message
                FROM {TDENGINE_DATABASE}.{TABLE_NAME}
                WHERE full_message LIKE '%{SEARCH_KEYWORD}%'
                ORDER BY ts DESC LIMIT 1
                """
                cursor.execute(sql)
                rows = cursor.fetchall()

                if rows:
                    latest_log = rows[0]
                    log_time = latest_log[0]
                    source_ip = latest_log[1]
                    message = latest_log[2]
                    translated_message = latest_log[3]

                    if last_sent_ts is None or log_time > last_sent_ts:
                        # 是新日志，发送邮件
                        subject = f"⚠️ 错误日志警报 - {source_ip}"
                        print(
                            f"📤 发送邮件内容: 时间: {log_time} | 来源IP: {source_ip} | "
                            f"原始日志内容: {message} | 翻译内容: {translated_message}"
                        )
                        body = (
                            f"时间: {log_time}\n"
                            f"来源IP: {source_ip}\n"
                            f"原始日志内容:\n{message}\n\n"
                            f"翻译内容:\n{translated_message}"
                        )
                        send_email(subject, body)
                        last_sent_ts = log_time  # 更新已发送时间
                    else:
                        print(f"✅ {time.strftime('%Y-%m-%d %H:%M:%S')} 无新 error 日志。")
                else:
                    print(f"✅ {time.strftime('%Y-%m-%d %H:%M:%S')} 当前没有 error 日志。")

            except Exception as inner_e:
                print(f"❌ 查询或处理出错: {inner_e}")

            time.sleep(POLL_INTERVAL_SECONDS)

    except Exception as e:
        print(f"❌ 无法连接 TDengine: {e}")
    finally:
        if conn:
            conn.close()
            print("✅ 连接已关闭。")

if __name__ == "__main__":
    monitor_tdengine()